package com.klod.api

import com.klod.data.bean.BaseResponseBean
import com.klod.data.mapping.NewsDetailBean
import com.klod.data.services.NewsServices
import com.klod.ext.responseFail
import com.klod.ext.responseSuccess
import io.ktor.http.*
import io.ktor.serialization.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.koin.java.KoinJavaComponent.inject

fun Application.configureNewsApi() {

    // Lazy inject
    val service by inject<NewsServices>(NewsServices::class.java)


    routing {

        route("/news") {
            get("/type") {
                call.respond(
                    service.types().responseSuccess()
                )


            }

            get("/list") {
                val page = call.parameters["page"]?.toInt() ?: 1
                val pageSize = call.parameters["pageSize"]?.toInt() ?: 10

                call.respond(
                    service.findAllNews(call.parameters["type"] ?: "", page, pageSize).responseSuccess()
                )


            }
            get("/detail") {
                call.respond(
                    service.findNewsById(call.parameters["id"]?.toInt() ?: -1).responseSuccess()

                )
//                    call.respondText("BannerList()")
            }
            post("addNews") {
                try {
                    call.respond(
                        service.addNews(call.receive<NewsDetailBean>()).responseSuccess()
                    )
                } catch (ex: IllegalStateException) {
                    call.respond(HttpStatusCode.BadRequest.description.responseFail())
                } catch (ex: JsonConvertException) {
                    call.respond(HttpStatusCode.BadRequest.description.responseFail())
                }
            }
            delete("delete") {
                val id = call.parameters["id"]?.toInt() ?: -1
                if (id == -1) {
                    call.respond(BaseResponseBean.fail("News ID 错误"))
                    return@delete
                }
                if (service.removeNews(id)) {
                    call.respond(HttpStatusCode.NoContent.responseSuccess())
                } else {
                    call.respond("没找到对应Id".responseFail())
                }

            }


        }

    }
}